package com.omronservice.web.scheduled;

import com.omronservice.app.curve.mapper.ExceptionCurveMapper;
import com.omronservice.utils.JacksonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by cool on 16/12/30.
 */
@Component
public class SPCTraceTask {
    private static final Logger log = LoggerFactory.getLogger(SPCTraceTask.class);

    //private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Autowired
    ExceptionCurveMapper exceptionCurveMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setRedisWaferidByab(Map map) {
        try {
            //String dateStr=dateFormat.format(new Date());
            String LINE_ID=map.get("LINE_ID").toString();
            String EQUIPMENT_ID=map.get("EQUIPMENT_ID").toString();
            String WAFER_ID=map.get("WAFER_ID").toString();
            String AB_TYPE=map.get("AB_TYPE").toString();
            String boolkey="SPCLIST_"+"_"+map.get("LINE_ID")+"_"+
                    map.get("EQUIPMENT_ID")+"_"+
                    map.get("AB_TYPE");
            stringRedisTemplate.opsForList().leftPush(boolkey, JacksonUtils.obj2json(map));
            //stringRedisTemplate.opsForValue().set(boolkey, JacksonUtils.obj2json(abAccompList));

        } catch (Exception e) {
            log.error("Exception========="+e.getMessage());
        }

    }
    public void saveAbEfficiency() {
        try {
            Set<String> keys=stringRedisTemplate.keys("SPCLIST_*");
            List list=new ArrayList();
            for (String key : keys) {
                int listsize=stringRedisTemplate.opsForList().size(key).intValue();
                String[] waferIDs=new String[listsize];
                String LINE_ID=null;
                Map mapAdd=null;
                for (int i=0;i>listsize;i++) {
                    Map map= JacksonUtils.json2map(stringRedisTemplate.opsForList().index(key,i));
                    String WAFER_ID=map.get("WAFER_ID").toString();
                    LINE_ID=map.get("LINE_ID").toString();
                    waferIDs[i]=WAFER_ID;
                    mapAdd=map;
                }
                String eat=exceptionCurveMapper.getEfficiency(LINE_ID,waferIDs);
                mapAdd.put("avgEat",eat);
                list.add(mapAdd);
                stringRedisTemplate.delete(key);
            }
            exceptionCurveMapper.insertEfficiency(list);
        } catch (Exception e) {
            log.error("Exception========="+e.getMessage());
        }

    }
}
